using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyRunner : MonoBehaviour
{
    [Header("Characteristics")]
    public int health;
    public int damage;
    private float speed;
    public float normalSpeed;
    public float stopInterval;
    private float stopTime;

    [Header("Reloading")]
    public float startTimeBtwAttack;
    private float timeBtwAttack;
    private Animator anim;
    private PlayerController player;
    private PlayerController SecondPlayer;
    private PlayerController nearest;
    private AddRoom room;

    [Header("Effects")]
    public GameObject floatingDamage;
    public GameObject deathEffect;

    // Получение объектов из окружения
    private void Start() {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
        if (PlayerPrefs.GetInt("playersCount") > 1) SecondPlayer = GameObject.FindGameObjectWithTag("SecondPlayer").GetComponent<PlayerController>();
        anim = GetComponent<Animator>();
        room = GetComponentInParent<AddRoom>();
    }

    private void Update() {   
        if (stopTime <= 0) { // Счётчик возобновления движения врага
            speed = normalSpeed;
        } else {
            speed = 0;
            stopTime -= Time.deltaTime;
        }

        if (health <= 0) { // Смерть врага           
            Instantiate(deathEffect, transform.position, Quaternion.identity);
            player.textScore.text = "SCORE: " + (player.score += 1);
            Destroy(gameObject);
            room.enemies.Remove(gameObject);
        }

        //Поворот врага
        if (player.transform.position.x > transform.position.x) transform.eulerAngles = new Vector3(0, 0, 0);
        else transform.eulerAngles = new Vector3(0, 180, 0);

        // Движение врага на игрока
        if (PlayerPrefs.GetInt("playersCount") > 1) {
            Vector3 difference_first = player.transform.position - transform.position;
            Vector3 difference_second = SecondPlayer.transform.position - transform.position;
            if (Vector3.Min(difference_first, difference_second) == difference_first) nearest = player;
            else nearest = SecondPlayer;
            transform.position = Vector2.MoveTowards(transform.position, nearest.transform.position, speed * Time.deltaTime);
        } else {
            transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
        }
    }

    // Нанесение урона
    public void TakeDamage(int damage) {
        stopTime = stopInterval;
        health -= damage;
        Vector2 damagePos = new Vector2(transform.position.x + 1f, transform.position.y + 1f); // Создание эффекта смерти врага
        Instantiate(floatingDamage, damagePos, Quaternion.identity);
        floatingDamage.GetComponentInChildren<FloatingDamage>().damage = damage;
        //Instantiate(deathEffect, player.transform.position, Quaternion.identity);
    }

    // Ближний бой
    public void OnTriggerStay2D(Collider2D other) {
        if(other.CompareTag("Player") || other.CompareTag("SecondPlayer")) {
            if(timeBtwAttack <= 0) anim.SetTrigger("enemyAttack");
            else timeBtwAttack -= Time.deltaTime;
        }
    }

    public void OnEnemyAttack() {
        //Instantiate(deathEffect, player.transform.position, Quaternion.identity);
        player.ChangeHealth(-damage);
        timeBtwAttack = startTimeBtwAttack;
    }
}
